package cn.wolfcode.filter;

import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class TimeGatewayFilterFactory extends AbstractGatewayFilterFactory<TimeGatewayFilterFactory.Config> {

    /**
     * Parts key.
     */
    public static final String PARTS_KEY = "parts";

    public TimeGatewayFilterFactory() {
        super(TimeGatewayFilterFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARTS_KEY);
    }

    public GatewayFilter apply(TimeGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange,
                                     GatewayFilterChain chain) {

//                System.out.println("前置逻辑");

                if(!config.isParts()){
                    return chain.filter(exchange);
                }
                /**
                 * 前置这里去记录一下时间
                 */
                exchange.getAttributes().put("beginTime",new Date().getTime());

                return chain.filter(exchange).then(Mono.fromRunnable(new Runnable() {
                    @Override
                    public void run() {
                        // 记录一下时间, 然后相减
                        System.out.println("后置逻辑");
                        long endTime = new Date().getTime();
                        long beginTime = (long) exchange.getAttributes().get("beginTime");
                        System.out.println("最终耗时"+(endTime-beginTime) +"ms");

                    }
                }));
            }
        };
    }

    @Getter
    @Setter
    public static class Config {
        private boolean parts;
    }
}